#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This program is free software; you can redistribute it and/or modify  
# it under the terms of the GNU General Public License as published by  
# the Free Software Foundation; either version 2 of the License, or     
# (at your option) any later version.                                   
#                                                                         
# A copy of the license can be found in the license.txt file supplied   
# with this software or at: http://www.gnu.org/copyleft/gpl.html       
#


import xml.dom.minidom


class   XmlHelper(object) :
    @staticmethod
    def getChildrenByPath(node_root, path) :
        children = []
        if not path : 
            return children

        tags = path.strip().split('/')
        node = node_root
        walk = 0 
        for tag in tags :
            walk += 1
            if not tag :
                continue
            children = XmlHelper.getChildren(node, tag)
            if not children :
                raise RuntimeError, 'Invalid XML path: "%s"' % '/'.join(tags[:walk])

            node = children[0]

        return children
        ## getChildrenByPath()

    @staticmethod
    def getChildren(node_parent, tag_child) :
        try :
            children = node_parent.getElementsByTagName( tag_child )
        except :
            children = []

        return children
        ## getChildren()

    @staticmethod
    def getNodeText(node) :
        text = ''
        for subnode in node.childNodes :
            if subnode.nodeType in ( xml.dom.Node.TEXT_NODE, xml.dom.Node.CDATA_SECTION_NODE):
                text = text + subnode.data

        return  text
        ## getNodetext()

    @staticmethod
    def getChildNodeTextByPath(node_root, path) :
        text = None

        try :
            children = XmlHelper.getChildrenByPath(node_root, path)
            for child in children :
                text = XmlHelper.getNodeText(child)
                if text : break
        except :
            pass

        return text
        ## getChildNodeTextByPath()

    @staticmethod
    def getChildNodeAttributeByPath(node_root, path, attribute) :
        text = None

        try :
            children = XmlHelper.getChildrenByPath(node_root, path)
            for child in children :
                text = child.getAttribute(attribute)
                if text : break
        except :
            pass

        return text
        ## getChildNodeTextByPath()


    ## class XmlHelper

